package id.co.shuba.spamobile.activities;

import java.util.ArrayList;
import java.util.List;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;

import id.co.shuba.spamobile.App;
import id.co.shuba.spamobile.CustomSessionApplication;
import id.co.shuba.spamobile.IDatePickerDialog;
import id.co.shuba.spamobile.IDatePickerTarget;
import id.co.shuba.spamobile.LogoutReceiver;
import id.co.shuba.spamobile.R;
import id.co.shuba.spamobile.Sessions;
import id.co.shuba.spamobile.data.AuditDB;
import id.co.shuba.spamobile.data.DatabaseHandler;
import id.co.shuba.spamobile.data.MaintenanceVisitDB;
import id.co.shuba.spamobile.data.StandardDB;
import id.co.shuba.spamobile.data.TransactionLogDB;
import id.co.shuba.spamobile.model.AuditInfo;
import id.co.shuba.spamobile.model.DSARInfo;
import id.co.shuba.spamobile.model.ErrorInfo;
import id.co.shuba.spamobile.model.MaintenanceVisitInfo;
import id.co.shuba.spamobile.model.ProspectInfo;
import id.co.shuba.spamobile.model.UserInfo;
import id.co.shuba.spamobile.util.AuditUtil;
import id.co.shuba.spamobile.util.DialogUtil;
import id.co.shuba.spamobile.util.SpinnerUtil;
import id.co.shuba.spamobile.util.Str;
import id.co.shuba.spamobile.util.ValidationUtil;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

public class FormMaintenanceVisitActivity extends SherlockActivity implements
		IDatePickerDialog, IDatePickerTarget {
	private static final int DATE_DIALOG_ID = 212;	
	
	private EditText txtAccountNo;
	private EditText txtDate;
	private EditText txtDebtorName;
	private Spinner spnObjectiveOfVisit;		
	
	private String defaultOption;
	
	private DatabaseHandler _db;	
	private MaintenanceVisitDB _maintenanceDB;
	private StandardDB _optionDB;
	private String _visitID;	
	private MaintenanceVisitInfo _info;
	
	private LogoutReceiver logoutReceiver;

	private void setUpLogoutReceiver() {
		IntentFilter intentFilter = new IntentFilter();
	    intentFilter.addAction("id.co.shuba.spamobile.ACTION_LOGOUT");
	    logoutReceiver = new LogoutReceiver(this);
	    registerReceiver(logoutReceiver, intentFilter);
	}
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
		getSupportMenuInflater().inflate(R.menu.activity_form_maintenance_visit, menu);
        return true;             
    }
	
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getTitle().equals(getString(R.string.save))) {
			save();
		}
		
	    return super.onOptionsItemSelected(item);
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_form_maintenance_visit);				
		setUpLogoutReceiver();
		setControls();

		_db = new DatabaseHandler(this);
		_maintenanceDB = new MaintenanceVisitDB(_db);
		_optionDB = new StandardDB(_db);

		defaultOption = getString(R.string.default_option);
		
		fillSpinner();						
		
		Intent intent = getIntent();
		_visitID = intent.getStringExtra("visitID");		
		
		if (_visitID != null) {
			setTitle("Ubah Maintenance Visit");
			_info = _maintenanceDB.get(_visitID);		
			loadData(_info);
		} else {
			setTitle("Buat Maintenance Visit");					
		}
	}		
	
	@Override protected void onStart() {
		super.onStart();
	}		
	
	private void fillSpinner() {		
		SpinnerUtil.fillStandard(this, _optionDB, spnObjectiveOfVisit, StandardDB.GROUP_OBJECTIVE_OF_VISIT, "V", defaultOption);		
	}

	private void setControls() {		
		txtDate = (EditText) findViewById(R.id.txtDate);
		txtAccountNo = (EditText) findViewById(R.id.txtAccountNo);
		txtDebtorName = (EditText) findViewById(R.id.txtDebtorName);
		
		spnObjectiveOfVisit = (Spinner) findViewById(R.id.spnObjectiveOfVisit);				
	}

	private void loadData(MaintenanceVisitInfo info) {
		String[] arr = info.getDateVisit().split(" ");
		txtDate.setText(DialogUtil.changeFormat(arr[0]));
		txtAccountNo.setText(info.getNoAccount());
		txtDebtorName.setText(info.getDebtorName());		
		SpinnerUtil.optionSetSelectedValue(spnObjectiveOfVisit, info.getObjectiveOfVisit());		
	}	
	
	private MaintenanceVisitInfo getData() {
		UserInfo user = Sessions.getUser(this);
		return getData(user);
	}
	
	private MaintenanceVisitInfo getData(UserInfo user) {
		MaintenanceVisitInfo info = new MaintenanceVisitInfo();		
				
		info.setAoCode(user.getAoCode());
		info.setUnitCode(user.getUnitCode());		
		info.setDateVisit(!Str.isNullOrEmpty(txtDate.getText().toString())? DialogUtil.changeFormat(txtDate.getText().toString()) + " 00:00:00": null);
		info.setNoAccount(txtAccountNo.getText().toString());
		info.setDebtorName(txtDebtorName.getText().toString());						
		info.setObjectiveOfVisit(SpinnerUtil.optionGetSelectedValue(spnObjectiveOfVisit, defaultOption));		
		
		String date = App.getProcessDateTime();
		
		if (_info == null) {
			info.setEntryBy(user.getNip());
			info.setEntryDate(date);
		} else {
			info.setEntryBy(_info.getEntryBy());
			info.setEntryDate(_info.getEntryDate());
		}	
		
		info.setUpdateBy(user.getNip());
		info.setUpdateDate(date);		
		
		info.setIsUpload("0");
		
		return info;
	}	
	
	private List<ErrorInfo> validate(MaintenanceVisitInfo info) {		
		List<ErrorInfo> errors = new ArrayList<ErrorInfo>();		
		if (!DialogUtil.isValidDateTime(info.getDateVisit()))
			errors.add(new ErrorInfo(txtDate, getString(R.string.visit_date)));
		if (Str.isNullOrEmpty(info.getNoAccount()))
			errors.add(new ErrorInfo(txtAccountNo, getString(R.string.account_no)));
		if (info.getNoAccount().length() > 15)
			errors.add(new ErrorInfo(txtAccountNo, getString(R.string.account_no), getString(R.string.account_no) + " maksimal 15 karakter"));
		
		if (Str.isNullOrEmpty(info.getDebtorName()))
			errors.add(new ErrorInfo(txtDebtorName, getString(R.string.debtor_name)));
		if (info.getDebtorName().length() > 50)
			errors.add(new ErrorInfo(txtDebtorName, getString(R.string.debtor_name), getString(R.string.debtor_name) + " maksimal 50 karakter"));
		if (info.getObjectiveOfVisit() == null)
			errors.add(new ErrorInfo(spnObjectiveOfVisit, getString(R.string.purpose)));		
		
		return errors;
	}						

	@Override
	protected void onDestroy() {
		unregisterReceiver(logoutReceiver);
		if (_db != null)
			_db.close();
		super.onDestroy();			
	}
	
	private void save() {
		try {
			UserInfo user = Sessions.getUser(this);
			MaintenanceVisitInfo info = getData(user);							
			
			List<ErrorInfo> errors = validate(info);
			
			if (errors.size() == 0) {				
				String action = "INSERT";
				if (_visitID == null) {		
					_visitID = String.valueOf(new java.util.Date().getTime());
					info.setId(_visitID);
					_maintenanceDB.add(info);
				} else {
					action = "UPDATE";
					info.setId(_visitID);					
					_maintenanceDB.update(info);
				}
				
				addTransactionLog(action, info);
				
				setResult(Activity.RESULT_OK);
				finish();
			} else {
				ValidationUtil.showValidationDialog(this, errors, this);
			}													
		} catch (Exception e) {
			e.printStackTrace();
		}		
	}	
	
	public void onDateDialogButtonClick(View v) {		
		showDialog(DATE_DIALOG_ID);
	}	
	
	private void addAuditTrail(MaintenanceVisitInfo info, String nip) throws Exception {		
		AuditDB audit = new AuditDB(_db);
		ArrayList<AuditInfo> list = AuditUtil.getAuditList(DSARInfo.class, _info , info, nip, defaultOption);		
		
		for (AuditInfo item : list) {
			audit.add(item);
		}		
	}
	
	private void addTransactionLog(String actType, MaintenanceVisitInfo info) throws Exception {
		TransactionLogDB trans = new TransactionLogDB(_db);
		String primaryKey = AuditUtil.getPrimaryKeyInfo(info);
		trans.add(info.getUpdateBy(), actType, String.format("%s %s", actType, primaryKey));
	}	

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DATE_DIALOG_ID:
			return DialogUtil.create(this, txtDate);
		}

		return null;
	}

	public void show(EditText txt) {		
		showDialog(DATE_DIALOG_ID);
	}

	public EditText getEditText() {		
		return txtDate;
	}
	
	@Override
	public void onBackPressed() {
		MaintenanceVisitInfo info = getData();
		boolean isChanged = false;
		try {
			isChanged = AuditUtil.isFormChanged(MaintenanceVisitInfo.class, _info, info, defaultOption);
		} catch (Exception e) {		
			e.printStackTrace();
		}	
		
		if (!isChanged) {
			finish();
			return;
		}
		
		new AlertDialog.Builder(new ContextThemeWrapper(this,
				R.style.Theme_Sherlock_Light_Dialog))
        .setIcon(android.R.drawable.ic_dialog_alert)
        .setTitle(R.string.confirm)
        .setMessage(R.string.save_changes)
        .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            	dialog.dismiss();
                save();    
            }
        })        
        .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {                
                finish();    
            }
        })
        .show();       
	}	
	
	@Override
	public void onUserInteraction() {		
		super.onUserInteraction();
		((CustomSessionApplication) getApplication()).touch();		
		if (App.DEBUG) {			
			Log.d("User Interaction", "User interaction to "+this.toString());			
		}
	}
}
